const inquirer = require('inquirer');
const async = require('async');

/**
 * 收集并挂载到data上
 * prompt可以添加一个when字段;
 * 该字段表示此prompt会根据when的值来判断是否出现在终端提示用户进行输入;
 * 在 vue-cli中, 其会根据when进行eval运算;
 * @param {object} data 
 * @description data是挂载到插件上的数据
 * @param {object} prompts 
 * @param {function} done 
 */
const prompt = (data = {}, prompts = {}, done) => {
    async.eachSeries(Object.keys(prompts), (name, callback) => {
        const question = prompts[name];

        if (question.when) {
            question.when = embellish(question.when, Object.prefix);
        }

        inquirer.prompt([{
            ...question,
            name: name
        }]).then(answer => {
            Object.assign(data, answer);
            Object.prefix = answer, callback();
        });
    }, done);
}

/**
 * 
 * @param {function} fn 
 * @param {object} object 
 */
const embellish = (fn, object) => {
    return 'function' === typeof fn ? fn.bind(object) : fn;
}

module.exports = prompt;